package com.katze.common.socket.server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketFileTransferRunnable implements Runnable{

    private final Socket client;

    public SocketFileTransferRunnable(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try (Socket socket = client;
             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
             OutputStream out = socket.getOutputStream()){
            Path file = Paths.get(reader.readLine());
            if (Files.exists(file)) {
                byte[] buffer = new byte[1024];
                try(InputStream in = Files.newInputStream(file)) {
                    for (int len = in.read(buffer); len != -1; len = in.read(buffer)) {
                        out.write(buffer, 0, len);
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
